package cn.edu.zju.gis.disasterBE.sever.controller;

import cn.edu.zju.gis.disasterBE.sever.dao.imageDownDao;
import cn.edu.zju.gis.disasterBE.sever.entity.imageQuery;
import cn.edu.zju.gis.disasterBE.sever.service.ImageDownService;
import cn.edu.zju.gis.disasterBE.sever.service.unZipFiles;
import cn.edu.zju.gis.disasterBE.sever.service.weatherService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.*;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static cn.edu.zju.gis.disasterBE.sever.dao.imageDownDao.midToFilename;

@RestController
public class ImageDownloadController {

    // Micro service download-callback handler
    @RequestMapping("/callback")
    public String callback(@RequestParam String sit, @RequestParam String id,@RequestHeader Map<String, String> headers)  throws IOException{

        System.out.print(sit);
        if(sit.equals("ok")){
            unZipFiles.unZipFiles(id);
            System.out.print(id + " download successfully\n");

        }
        else if(sit.equals("done")){
            imageDownDao.downloaded(id);
            System.out.print(id + " all successfully\n");
        }
        else if(sit.equals("fail")){
            System.out.print(id + " download failed\n");
        }
        else if(sit.equals("timeout")){
            System.out.print(id + " download timeout\n");
        }
        return "ok";
    }
    // Get all disaster id
    @RequestMapping("/selectAll")
    public List<imageQuery> selectAll()  {

        return ImageDownService.selectAll();

    }

    // Search and insert metadate of images
    @RequestMapping("/search")
    public String down(@RequestParam Double lat, @RequestParam Double lng , @RequestParam int did, @RequestParam
        Timestamp beginPosition,@RequestParam
        Timestamp endPosition, @RequestParam String aoi) throws DocumentException {

        ImageDownService.imageSearch(lat,lng,did,beginPosition,endPosition,aoi,"0");
        ImageDownService.imageSearch(lat,lng,did,beginPosition,endPosition,aoi,"100");
        //ImageDownService.imageSearch(lat,lng,did,"200");

        return "ok";
    }

    // Get the preview of the image
    @RequestMapping("/preview")
    public ResponseEntity< byte[]> down(@RequestParam String id) throws DocumentException {
        RestTemplate restTemplate = new RestTemplate();

        String url =  "https://scihub.copernicus.eu/dhus/odata/v1/Products('"+id+"')/Products('Quicklook')/$value";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic emhhbmdmZW5nOnpoYW5nZmVuZ2RhcWlhbg==");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity< byte[]> response = restTemplate.exchange(url,HttpMethod.GET,entity, byte[].class);

        return response;
    }

    // Download from server
    @RestController
    @RequestMapping("file")
    public class downloadFile {
        @GetMapping("/downloadfile")
        public ResponseEntity<FileSystemResource> downloadFile(@RequestParam String id) {
            //String path = "C:/Users/SeedlingYou/Desktop/" + id + "/" + id + ".tiff";
            String path = "/root/imageStore/" + id + "/" + id + ".tiff";
            String filename = midToFilename(id);

            return export(new File(path),filename);
        }

        public ResponseEntity<FileSystemResource> export(File file, String name) {
            if (file == null) {
                return null;
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + name + ".TIFF");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));
            FileSystemResource r = new FileSystemResource(file);
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new FileSystemResource(file));
        }
    }

    // Download from ESA
    @RequestMapping("/download")
    public String downloadNet(@RequestParam String id) throws IOException {

        //String path = "C:/Users/SeedlingYou/Desktop/21";
        String path = "/root/imageStore";

        //ImageDownService.imageDownload(id, path);

        //http请求，转码，输入id
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://127.0.0.1:10001/download?id=" + id;
        restTemplate.getForObject(url,String.class);

        return "Sorry, the image is not in our server now! But, we start to download from the internet.";
/*        //http请求转COG

        RestTemplate restTemplate2 = new RestTemplate();
        String url2 = "http://127.0.0.1:10001/convert?input=" + id;
        restTemplate2.getForObject(url2,String.class);*
 */

    }

    // Get weather information
    @RequestMapping("/weather")
    public String weather(@RequestParam Double lat, @RequestParam Double lng, @RequestParam Integer y,@RequestParam Integer m ,@RequestParam Integer d){

        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.stormglass.io/v2/weather/point";
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        builder.queryParam("lat",lat);
        builder.queryParam("lng",lng);
        builder.queryParam("params","airTemperature,precipitation,cloudCover");
        //waterTemperature, wavePeriod, waveDirection, waveHeight, windWaveDirection, windWaveHeight, windWavePeriod, swellPeriod, secondarySwellPeriod, swellDirection, secondarySwellDirection, swellHeight, secondarySwellHeight, windSpeed, windSpeed20m, windSpeed30m, windSpeed40m, windSpeed50m, windSpeed80m, windSpeed100m, windSpeed1000hpa, windSpeed800hpa, windSpeed500hpa, windSpeed200hpa, windDirection, windDirection20m, windDirection30m, windDirection40m, windDirection50m, windDirection80m, windDirection100m, windDirection1000hpa, windDirection800hpa, windDirection500hpa, windDirection200hpa, airTemperature, airTemperature80m, airTemperature100m, airTemperature1000hpa, airTemperature800hpa, airTemperature500hpa, airTemperature200hpa, precipitation, gust, cloudCover, humidity, pressure, visibility, currentSpeed, currentDirection, iceCover, snowDepth, seaLevel


        //cloudCover 加进去
        Calendar c = Calendar.getInstance();
        c.set(y,m+1,d); //月份下标从0开始
        int threeDays = 3600*24*3;
        builder.queryParam("start",c.getTimeInMillis()/1000-threeDays);
        builder.queryParam("end",c.getTimeInMillis()/1000+threeDays);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization","3e67b344-e7c4-11eb-862d-0242ac130002-3e67b3bc-e7c4-11eb-862d-0242ac130002");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

        ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(),HttpMethod.GET,entity,String.class);
        String body = response.getBody();

        weatherService.writedb(body,19260817,lat ,lng);

        return body;
    }

    // Resolve the xml
    @RequestMapping(value = "/resolve", method = {RequestMethod.POST})
    public String resolve(@RequestParam(required = false) MultipartFile file) {
        try {
            resolveXml(file);
            return "yes";
        } catch (Exception var3) {
            return "no";
        }
    }

    public void resolveXml(MultipartFile file) throws Exception{
        SAXReader reader = new SAXReader();
        InputStream is = file.getInputStream();
        Document doc = reader.read(is);
        Element root = doc.getRootElement();
        System.out.println(root.element("PRODUCT_URI"));
    }

    // Upload the image
    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
    public String upload(@RequestParam(required = false) String mid, @RequestParam(required = false) String title,
                         @RequestParam(required = false) String platFormName, @RequestParam(required = false) String productType,
                         @RequestParam(required = false) String date, @RequestParam(required = false) String resolution,
                         @RequestParam(required = false) String instrumentname, @RequestParam(required = false) String cloudcoverpercentage,
                          @RequestParam(required = false) String disasterId, @RequestParam(required = false) String dir, @RequestParam(required = false) MultipartFile file) {
        try {
            imageQuery iQ = new imageQuery();
            iQ.did = Integer.parseInt(disasterId);
            iQ.id = mid;
            iQ.title = title;
            iQ.platformname = platFormName;
            iQ.producttype = productType;
            iQ.date = date;
            iQ.resolution = Double.parseDouble(resolution);
            iQ.instrumentname = instrumentname;
            iQ.orbitnumber = -1;
            iQ.cloudcoverpercentage = Double.parseDouble(cloudcoverpercentage);

            System.out.print(title+"ytfjygugkugkuhuguguiguigugugkug");
            System.out.println("upload start = " + System.currentTimeMillis());
            String videoUrl = uploadFile(file, mid);
            System.out.println("upload end = " + System.currentTimeMillis());
            System.out.print(mid);
            imageDownDao.write(iQ);
            return "yes";
        } catch (Exception var3) {
            return "no";
        }
    }

    public String uploadFile(MultipartFile file, String mid) throws Exception {
        //String shortPath =  file.getOriginalFilename();
        String shortPath =  mid + ".tiff";

        File dest = new File("/root/imageStore/"+mid+"/", shortPath);
        if (!dest.getParentFile().exists()) {
            boolean rel = dest.getParentFile().mkdirs();
            if (!rel) {
                throw new Exception("文件夹创建失败");
            }
        }
        InputStream is = file.getInputStream();
        OutputStream os = new FileOutputStream(dest);
        try {
            byte[] buffer = new byte[8 * 1024];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
        return shortPath;
    }

    @RequestMapping("/fuck")
    public String fuck()  {

        return "FUCK";

    }
}
